import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
import { getUnique } from '@/utils/auth'
import { ElNotification } from 'element-plus'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['x-unique'] = getUnique() //加入token到请求头
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code == 200) {
      return res
    } else {
      console.log(res);
      ElNotification({
        title: res.msg,
        message: (res.data && typeof res.data.err != 'undefined') ? "详细信息：" + res.data.err : undefined,
        type: 'warning'
      })
      return Promise.reject({ ...res, erroe: new Error(res.msg || 'Error') })
    }
  },
  error => {
    console.log('err' + error) // for debug
    ElNotification({
      title: '未知错误',
      message: "详细信息：" + error,
      type: 'error'
    })
    // return Promise.reject(error)
    return Promise.reject({ 
      code: 4, 
      msg: '未知错误', 
      erroe: error
    })
  }
)

export default service
